package org.dromara.vehicle.modules.configDistrict.service.impl;

import cn.hutool.core.text.StrSplitter;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.CacheConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.vehicle.modules.configDistrict.domain.GeoConfigDistrict;
import org.dromara.vehicle.modules.configDistrict.mapper.GeoConfigDistrictMapper;
import org.dromara.vehicle.modules.configDistrict.service.GeoConfigDistrictService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 行政区域坐标库(GeoConfigDistrict)表服务实现类
 *
 * @author ckk
 * @since 2025-07-08 22:19:17
 */
@RequiredArgsConstructor
@Service
public class GeoConfigDistrictServiceImpl extends ServiceImpl<GeoConfigDistrictMapper, GeoConfigDistrict> implements GeoConfigDistrictService {

    private final GeoConfigDistrictMapper baseMapper;

    @Value("${gaoDe.api-key}")
    private String apiKey;

    /**
     * 获取选区边界
     *
     * @param adCode 广告代码
     * @return {@link List }<{@link List }<{@link double[] }>>
     */
    @Override
    @Cacheable(cacheNames = CacheConstants.DISTRICT_BOUNDARY_KEY, key = "#adCode", condition = "#adCode != null")
    public List<List<double[]>> getDistrictBoundaries(String adCode) {

        GeoConfigDistrict vo = baseMapper.selectById(adCode);
        if (vo != null) {
            return parseBoundaries(vo.getName());
        }

        String url = "https://restapi.amap.com/v5/config/district?" +
            "keywords=" + adCode +
            "&key=" + apiKey +
            "&subdistrict=0&extensions=all";

        // 发送 HTTP 请求
        String response = HttpUtil.get(url);

        // 解析 JSON 响应
        JSONObject result = JSONUtil.parseObj(response);

        if (!"1".equals(result.getStr("status"))) {
            throw new ServiceException("API调用失败: " + result.getStr("info"));
        }

        // 提取行政区划数据
        List<JSONObject> districts = result.getJSONArray("districts").toList(JSONObject.class);
        if (districts.isEmpty()) {
            throw new ServiceException("未找到行政区划数据");
        }

        String polyline = districts.get(0).getStr("polyline");

        GeoConfigDistrict configDistrict = new GeoConfigDistrict();
        configDistrict.setId(adCode);
        configDistrict.setName(polyline);
        baseMapper.insert(configDistrict);

        return parseBoundaries(polyline);
    }

    /**
     * 解析边界坐标字符串
     */
    private List<List<double[]>> parseBoundaries(String polylineStr) {
        List<List<double[]>> boundaries = new ArrayList<>();

        //  分割多边形数据（按分隔符 ; 分割）
        for (String pointStr : StrSplitter.split(polylineStr, ';')) {
            List<double[]> polygon = new ArrayList<>();
            String[] coords = StrSplitter.splitToArray(pointStr, ',');
            polygon.add(new double[]{
                Double.parseDouble(coords[0]), // 经度（原数据格式：经度,纬度）
                Double.parseDouble(coords[1])  // 纬度
            });
            boundaries.add(polygon);
        }

        return boundaries;
    }
}

